<template>
  <div class="openOrder">
    <!-- 顶部查询表单 -->
    <div class="openOrderTop">
      <el-form ref="searchForm" :model="queryParam" :inline="true" size="mini">
        <!-- <el-col :span="5"> -->
        <el-form-item label="供应商：" prop="customer">
          <el-select clearable filterable v-model="queryParam.customerInfo" style="width: 170px">
            <el-option :key="item.id" :label="item.name" :value="item.id" v-for="item in payCustomerDropdowm"></el-option>
          </el-select>
        </el-form-item>
        <!-- </el-col> -->
        <!-- <el-col :span="5"> -->
        <el-form-item label="结算单编号：">
          <el-input clearable placeholder="请输入结算单编号" size="mini" style="width: 170px" v-model="queryParam.billCode"></el-input>
        </el-form-item>
        <el-form-item label="发票代码：">
          <el-input clearable placeholder="请输入发票代码" size="mini" style="width: 170px" v-model="queryParam.cbDocumentCode"></el-input>
        </el-form-item>
        <!-- </el-col> -->
        <!-- <el-col :span="8"> -->
        <el-form-item label="结算时间：">
          <el-date-picker clearable placeholder="请选择开始时间" style="width: 170px" type="datetime" v-model="queryParam.startTime"></el-date-picker>
          -
          <el-date-picker clearable placeholder="请选择结束时间" style="width: 170px" type="datetime" v-model="queryParam.endTime"></el-date-picker>
        </el-form-item>
        <!-- </el-col> -->
        <el-form-item label="委托书编号:">
          <el-input clearable size="mini" placeholder="请输入委托书编号" style="width: 170px" v-model="queryParam.contractNo"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="initMainTable">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 按钮组 -->
    <div class="openTitle">对账单列表</div>
    <div class="btn">
      <buttonName @clickEvent="clickEvent"></buttonName>
    </div>
    <!-- 主要表格 -->
    <split-pane split="horizontal" v-on:resize="resize" :min-percent="20" :default-percent="55">
      <template slot="paneL">
        <div class="openOrderBox" ref="tableH" style="height: 100%">
          <!-- 结算单列表 表格 -->
          <el-tabs v-model="actionName" :height="maxHeight" type="card" @tab-click="tabsClick">
            <el-tab-pane label="陆运结算" name="way">
              <div class="openLeftTableBox">
                <el-table
                  :data="mainPayDataTable.data"
                  border
                  ref="wayTableRef"
                  :header-cell-style="{ textAlign: 'center' }"
                  @row-click="mainTableRowClick"
                  @selection-change="selectionChange"
                  :height="maxHeight"
                  :row-style="rowStyleHandler"
                >
                  <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
                  <el-table-column align="center" type="selection"></el-table-column>
                  <el-table-column align="center" prop="status" label="状态" show-overflow-tooltip width="150">
                    <template slot-scope="scope">
                      {{ showStatus(scope.row) }}
                    </template>
                  </el-table-column>
                  <el-table-column align="center" prop="type" label="费目" show-overflow-tooltip width="150"></el-table-column>
                  <el-table-column align="center" prop="name" label="结算单名称" show-overflow-tooltip width="150"></el-table-column>
                  <el-table-column align="center" prop="code" label="结算单号" show-overflow-tooltip width="250">
                    <template slot-scope="scope">
                      <u @click="showDetail(scope.row)">{{ scope.row.code }}</u>
                    </template>
                  </el-table-column>
                  <el-table-column align="center" prop="acode" label="订单号" show-overflow-tooltip width="200"></el-table-column>
                  <el-table-column align="center" width="120px" label="结算对象" show-overflow-tooltip>
                    <template slot-scope="scope">{{ scope.row.together == 'Y' ? scope.row.sourcePayName : scope.row.payName }}</template>
                  </el-table-column>
                  <el-table-column align="center" prop="cmtNo" label="委托书编号" show-overflow-tooltip width="200"></el-table-column>
                  <el-table-column align="center" prop="documentCodes" label="发票代码" show-overflow-tooltip width="250"></el-table-column>
                  <el-table-column align="center" prop="cbReceiveDocumentDate" label="收票时间" show-overflow-tooltip width="200"></el-table-column>
                  <el-table-column align="center" prop="loadingPlace" label="装货地点" show-overflow-tooltip></el-table-column>
                  <el-table-column align="center" prop="unloadPlace" label="收货地点" show-overflow-tooltip></el-table-column>
                  <el-table-column align="center" prop="weight" label="吨数" show-overflow-tooltip></el-table-column>
                  <el-table-column align="center" prop="price" label="单价(元/吨)" show-overflow-tooltip width="150"></el-table-column>
                  <el-table-column align="center" prop="totalPrice" label="金额(元)" show-overflow-tooltip></el-table-column>
                  <el-table-column align="center" prop="remark" label="备注" show-overflow-tooltip></el-table-column>
                </el-table>
              </div>
              <!-- 分页 -->
              <div class="block">
                <el-pagination
                  ref="pagination"
                  small
                  background
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="Pagination.currentPage"
                  :page-sizes="Pagination.pageSizeList"
                  :page-size="Pagination.PageSize"
                  :layout="Pagination.layout"
                  :total="Pagination.total"
                ></el-pagination>
              </div>
            </el-tab-pane>
            <el-tab-pane name="sea" label="海运结算">
              <el-table
                :data="infoPayTable.data"
                border
                ref="seaTableRef"
                :header-cell-style="{ textAlign: 'center' }"
                highlight-current-row
                @row-click="mainTableRowClick"
                :height="maxHeight"
                @selection-change="selectionChange"
              >
                <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
                <el-table-column align="center" type="selection"></el-table-column>
                <el-table-column align="center" prop="status" label="状态" width="100" show-overflow-tooltip></el-table-column>
                <el-table-column align="center" prop="type" label="费目" show-overflow-tooltip></el-table-column>
                <el-table-column align="center" prop="name" label="结算单名称" show-overflow-tooltip width="150"></el-table-column>
                <el-table-column align="center" prop="code" label="结算单号" show-overflow-tooltip width="250"></el-table-column>
                <el-table-column align="center" prop="acode" label="订单号" show-overflow-tooltip width="200"></el-table-column>
                <el-table-column align="center" width="120px" prop="payName" label="结算对象" show-overflow-tooltip></el-table-column>
                <el-table-column align="center" prop="cmtNo" label="委托书编号" show-overflow-tooltip width="200"></el-table-column>
                <el-table-column align="center" prop="loadingPlace" label="装货地点" show-overflow-tooltip></el-table-column>
                <el-table-column align="center" prop="unloadPlace" label="收货地点" show-overflow-tooltip></el-table-column>
                <el-table-column align="center" prop="weight" label="总重(吨)" show-overflow-tooltip></el-table-column>
                <el-table-column align="center" prop="price" label="单价(元/吨)" show-overflow-tooltip width="120"></el-table-column>
                <el-table-column align="center" prop="totalPrice" label="金额(元)" show-overflow-tooltip></el-table-column>
                <el-table-column align="center" prop="remark" label="备注" show-overflow-tooltip></el-table-column>
              </el-table>
              <div class="block">
                <el-pagination
                  class="pagination"
                  small
                  background
                  @size-change="infoHandleSizeChange"
                  @current-change="infoHandleCurrentChange"
                  :current-page="infoPayTable.pageInfo.index"
                  :page-sizes="Pagination.pageSizeList"
                  :page-size="infoPayTable.pageInfo.size"
                  :layout="Pagination.layout"
                  :total="infoPayTable.pageInfo.total"
                ></el-pagination>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </template>
      <template slot="paneR">
        <div ref="billItemRef" style="height: 80%">
          <el-table :data="billItemTable.data" border :height="itemHeight">
            <el-table-column width="55" show-overflow-tooltip align="center" type="index" label="序号"></el-table-column>
            <el-table-column show-overflow-tooltip align="center" prop="conNo" label="委托书编号" width="180"></el-table-column>
            <el-table-column show-overflow-tooltip align="center" prop="wcdSttime" label="装货日期" width="180"></el-table-column>
            <el-table-column show-overflow-tooltip align="center" prop="startPlace" label="装货地点" width="200"></el-table-column>
            <el-table-column show-overflow-tooltip align="center" prop="endPlace" label="收获地点" width="200"></el-table-column>
            <el-table-column show-overflow-tooltip align="center" prop="goodsName" label="货名"></el-table-column>
            <el-table-column show-overflow-tooltip align="center" prop="trkNo" label="车号"></el-table-column>
            <el-table-column show-overflow-tooltip align="center" prop="allWeight" label="吨数"></el-table-column>
            <el-table-column show-overflow-tooltip align="center" prop="ctrNo" label="箱号" v-if="actionName == 'sea'"></el-table-column>
            <el-table-column show-overflow-tooltip align="center" prop="sealNo" label="铅封号" v-if="actionName == 'sea'"></el-table-column>
            <el-table-column show-overflow-tooltip align="center" prop="transportQuantity" label="费用信息">
              <el-table-column show-overflow-tooltip align="center" prop="price" label="运输单价(元/吨)" width="150"></el-table-column>
              <el-table-column show-overflow-tooltip align="center" prop="allWeight" label="总重(吨)"></el-table-column>
              <el-table-column show-overflow-tooltip align="center" prop="allPrice" label="费用" width="150"></el-table-column>
            </el-table-column>
          </el-table>
        </div>
      </template>
    </split-pane>

    <!-- 结算单查看 dialog -->
    <viewDialog :info="viewDialogData" @dialogClose="dialogClose"></viewDialog>
    <!-- 增删改查 dialog -->
    <infoDialog :info="infoDialogData" @dialogClose="dialogClose"></infoDialog>

    <el-dialog
      :title="receiveDocumentDateDialog.title"
      :visible.sync="receiveDocumentDateDialog.show"
      :close-on-click-modal="false"
      v-el-drag-dialog
      v-dialogDrag
      width="20%"
    >
      <el-form :model="receiveDocumentDateDialog" ref="receiveForm" inline size="mini">
        <el-form-item label="收款日期：" prop="date" :rules="[{ required: true, message: '请选择收款日期', trigger: 'blur' }]">
          <el-date-picker value-format="yyyy年MM月dd日" v-model="receiveDocumentDateDialog.date" placeholder="选择日期" type="date"></el-date-picker>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="receiveDocumentDateDialogClose">取 消</el-button>
        <el-button size="mini" type="primary" @click="doReceiveDocumentDate">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="reviewDialog.title"
      :visible.sync="reviewDialog.show"
      :close-on-click-modal="false"
      v-el-drag-dialog
      v-dialogDrag
      width="30%"
      @close="reviewDialogClose"
    >
      <el-row align="center">
        <el-col align="center">
          <el-upload
            :data="reviewDialog.data"
            ref="reviewUploadFileRef"
            class="upload-demo"
            drag
            :file-list="reviewDialog.fileList"
            :action="uploadAction"
            :auto-upload="false"
            multiple
            name="file"
            :on-success="reviewFileUploadSuccess"
            :on-error="reviewFileUploadError"
            :headers="{ Token: $store.state.user.Session_Token, pageUrl: $store.state.app.mdlUrl.replace('/layout', '') }"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">文件不超过5M</div>
          </el-upload>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="reviewDialog.show = false">取 消</el-button>
        <el-button size="mini" type="primary" @click="doCheck">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import paginationMixin from '@/mixins/pagination'
import isAuth from '@/mixins/buttonAuth'
import viewDialog from '@/views/cstManagement/twoCstManagement/expenseSettlement/viewDialog'
import infoDialog from '@/views/settlement/towSettlement/receivable/infoDialog'
import resizeMixin from '@/mixins/resize'
import {
  confirmationResultsList,
  exportStatement,
  queryBillItem,
  queryPlatformCustomerDropDownBill,
  queryPlatformWithSupplierBill,
  updateBillsSelective,
} from '@/request/api'
import buttonName from '@/components/buttonName/button-name'

export default {
  name: 'router.openOrderManage',
  mixins: [resizeMixin, paginationMixin, isAuth],
  data() {
    return {
      selected: [],
      feeInfoDisable: false,
      confirmDisable: false,
      isThirdData: {
        Y: '已发起结算',
        N: '未发起结算',
      },
      currentData: {},
      actionName: 'way',
      maxHeight: -1,
      itemHeight: -1,
      // 下拉框
      payCustomerDropdowm: [], // 结算对象下拉
      queryParam: {
        customerInfo: '', // 结算对象
        billCode: '', // 结算单编号
        startTime: null,
        endTime: null,
        contractNo: '',
        cbDocumentCode: '', // 发票代码
      },
      // 页面结算对象表格
      mainPayDataTable: {
        data: [],
        currentData: {},
      },
      // 查看dialog
      viewDialogData: {
        title: '',
        show: false,
        currentData: {},
        btn: '',
        btnShow: true,
        reconciliation: true, // 显示文字
        source: 2,
        tagName: '',
        uploadFileShow: false,
        yht: 'gys',
      },
      infoPayTable: {
        data: [],
        currentData: {},
        pageInfo: {
          index: 1,
          size: 30,
          total: 0,
        },
      },
      billItemTable: {
        data: [],
      },
      infoDialogData: {
        show: false,
        title: undefined,
        data: undefined,
        billFromShow: false,
      },
      cbIsInfoData: {
        Y: '是',
        N: '否',
      },
      receiveDocumentDateDialog: {
        show: false,
        title: '',
        date: undefined,
      },
      reviewDialog: {
        show: false,
        title: '',
        data: {
          json: '',
        },
        fileList: [],
      },
    }
  },
  components: {
    viewDialog,
    infoDialog,
    buttonName,
  },
  computed: {
    uploadAction() {
      return (process.env.NODE_ENV === 'production' ? '' : '/proxy') + '/FTKJWLHYPT/bill/reviewUploadFile'
    },
    showStatus() {
      return row => {
        const status = row.status
        if (status === '已发起收款') {
          return '对方发起收款'
        }
        return status
      }
    },
  },
  created() {
    this.resize = () => {
      this.maxHeight = this.$refs.tableH.offsetHeight - 100
      this.itemHeight = this.$refs.billItemRef.offsetHeight
    }
  },
  mounted() {
    this.initMainTable()
    this.initPayCustomerDropdowm()
  },
  methods: {
    rowStyleHandler({ row }) {
      if (this.selected.includes(row)) {
        return {
          background: '#5786ee',
        }
      }
    },
    clickEvent(val) {
      if (val.mdlCode === 'confirmPayment') {
        this.confirmPayment()
      }
      if (val.mdlCode === 'platformConfirm') {
        this.platformConfirmBtn()
      }
      if (val.mdlCode === 'confirmPCollect') {
        this.confirmPCollect()
      }
      if (val.mdlCode === 'feeInfo') {
        this.feeInfo()
      }
      if (val.mdlCode === 'print') {
        this.print()
      }
      if (val.mdlCode === 'check') {
        this.check()
      }
      if ('receiveDocumentDate' === val.mdlCode) {
        this.receiveDocumentDate()
      }
    },
    // 初始化主表
    initMainTable() {
      queryPlatformWithSupplierBill({
        cbJpayer: this.queryParam.customerInfo,
        index: this.currentActionName == 'way' ? this.Pagination.currentPage : this.infoPayTable.pageInfo.index,
        size: this.currentActionName == 'way' ? this.Pagination.pageSize : this.infoPayTable.pageInfo.size,
        cbBillType: this.queryParam.billType,
        cbType: this.actionName,
        cbBillNo: this.queryParam.billCode,
        startTime: this.queryParam.startTime,
        endTime: this.queryParam.endTime,
        contractNo: this.queryParam.contractNo,
        cbDocumentCode: this.queryParam.cbDocumentCode,
      }).then(res => {
        if (this.actionName == 'way') {
          this.mainPayDataTable.data = res.data
          this.updatePaginationTotal(res.total)
        } else {
          this.infoPayTable.data = res.data
          this.infoPayTable.pageInfo.total = res.total
        }
        this.confirmDisable = false
        this.feeInfoDisable = false
      })
    },
    // 初始化下拉框
    initPayCustomerDropdowm() {
      queryPlatformCustomerDropDownBill({}).then(res => {
        this.payCustomerDropdowm = res.data
      })
    },
    initBillItemTable() {
      queryBillItem({
        billId: this.currentData.id,
      }).then(res => {
        this.billItemTable.data = res.data
      })
    },
    getList() {
      this.initMainTable()
    },
    // 打印
    print() {
      const data = this.selected
      if (!data.length) {
        this.$message.error({
          message: '至少选择一项',
          showClose: true,
        })
        return
      }
      for (let datum of data) {
        if (datum.payName !== data[0].payName) {
          this.$message.error({
            message: '请选择相同的结算对象',
            showClose: false,
          })
          return
        }
      }
      exportStatement({
        ids: data.map(value => {
          return value.id
        }),
        type: 0,
        yht: 'gys',
        section: this.actionName,
      }).then(res => {
        const fileName = decodeURI(res.headers['filename'])
        const reader = new FileReader()
        reader.readAsDataURL(new Blob([res.data]))
        reader.onload = e => {
          let a = document.createElement('a')
          a.download = fileName
          a.href = e.target.result
          document.body.appendChild(a)
          a.click()
          document.body.removeChild(a)
        }
        window.parent._$store.dispatch('app/loading_status', false)
        this.initMainTable()
      })
    },
    // 平台确认
    check() {
      if (!this.selected.length) {
        this.$message.error({
          showClose: false,
          message: '至少选择一项',
        })
        return
      }
      for (let item of this.selected) {
        if (item.statusCode.toString() === '3') {
          this.$message.error({
            message: '不要重复确认',
            showClose: true,
          })
          return
        }
        if (item.statusCode.toString() !== 'PUSH') {
          this.$message.error({
            message: '请选择对方推送数据',
            showClose: true,
          })
          return
        }
      }
      this.reviewDialog.show = true
      this.reviewDialog.title = '添加附件'
    },
    reviewFileUploadSuccess(res, file, fileList) {
      for (let item of fileList) {
        if (item.status !== 'success') {
          return
        }
      }
      this.reviewDialog.show = false
      this.$message.success('上传成功')
      this.$refs['reviewUploadFileRef'].clearFiles()
    },
    reviewFileUploadError(err, file, fileList) {
      this.$message.error(`${file.name}上传失败`)
    },
    doCheck() {
      if (!this.$refs['reviewUploadFileRef'].uploadFiles.length) {
        this.$message.error('至少添加一个附件')
        return
      }
      this.reviewDialog.data.json = JSON.stringify(
        Object.assign({}, this.selected[0], {
          documents: [],
          cbEditer: this.$store.state.user.USR_CODE_DX_H,
          cbBillStatus: '3',
          cbId: this.selected[0].id,
        })
      )
      this.$refs['reviewUploadFileRef'].submit()
    },
    reviewDialogClose() {
      this.initMainTable()
      this.reviewDialog.data.json = ''
    },
    // 收款确认
    confirmPCollect() {
      if (Object.keys(this.currentData).length == 0) {
        this.$message.error('至少选择一项')
        return
      }
      if (this.currentData.statusCode == 5) {
        this.$message.error('不要重复确认')
        return
      }
      if (this.currentData.statusCode != 4) {
        this.$message.error('账单状态异常，请刷新页面')
        return
      }
      this.viewDialogData.currentData = this.currentData
      this.viewDialogData.currentData.interimStatus = '5'
      this.viewDialogData.title = '收款确认'
      this.viewDialogData.btn = '确定'
      this.viewDialogData.btnShow = true
      this.viewDialogData.show = true
      this.viewDialogData.uploadFileShow = false
    },
    // 付款确认
    confirmPayment() {
      if (!this.selected.length) {
        this.$message.error({
          showClose: false,
          message: '至少选择一项',
        })
        return
      }
      for (let datum of this.selected) {
        if (datum.statusCode.toString() === '4') {
          this.$message.error({
            message: `${datum.code}不要重复确认`,
            showClose: true,
          })
          return
        }
        if (datum.statusCode.toString() !== '2') {
          this.$message.error({
            message: `${datum.code}账单不是发起状态`,
            showClose: true,
          })
          return
        }
      }
      confirmationResultsList({
        ids: this.selected.map(value => {
          return value.id
        }),
        status: '4',
      }).then(() => {
        this.$message.success({
          showClose: true,
          message: '付款确认成功',
        })
        this.initMainTable()
      })
    },
    mainTableRowClick(val) {
      this.$refs[`${this.actionName}TableRef`].toggleRowSelection(val)
      this.currentData = val
      this.confirmDisable = val.together == 'Y'
      this.feeInfoDisable = val.cbIsInfo == 'Y'
      this.initBillItemTable()
    },
    tabsClick({ name }) {
      this.selected = []
      this.actionName = name
      this.viewDialogData.tagName = name
      this.initMainTable()
    },
    platformConfirmBtn() {
      if (Object.keys(this.currentData).length == 0) {
        this.$message.error('至少选择一项')
        return
      }
      if (this.currentData.isThird == 'Y') {
        this.$message.error('无法重复发起结算')
        return
      }
      this.viewDialogData.btn = '确认'
      this.viewDialogData.btnShow = true
      this.viewDialogData.documentNoDisable = false
      this.viewDialogData.currentData = this.currentData
      this.viewDialogData.uploadFileShow = true
      this.viewDialogData.billItemTableShow = true
      this.viewDialogData.show = true
      this.viewDialogData.title = '向客户发起结算'
    },
    dialogClose() {
      this.currentData = {}
      this.initMainTable()
    },
    // 服务费结算
    feeInfo() {
      if (Object.keys(this.currentData).length === 0) {
        this.$message.error('请选择一项')
        return
      }
      if (this.currentData.cbIsInfo === 'Y') {
        this.$message.error('已经结算服务费，无法重复结算')
        return
      }
      this.infoDialogData.title = '服务费结算'
      this.infoDialogData.data = this.currentData
      this.infoDialogData.show = true
    },
    selectionChange(rows) {
      this.selected = rows
    },
    showDetail(row) {
      this.viewDialogData.currentData = row
      this.viewDialogData.documentNoDisable = true
      this.viewDialogData.uploadFileShow = false
      this.viewDialogData.btnShow = false
      this.viewDialogData.title = '详细信息'
      this.viewDialogData.show = true
      this.viewDialogData.tagName = this.actionName
    },
    receiveDocumentDate() {
      if (!this.selected.length) {
        this.$message.error('至少选择一项')
        return
      }
      this.receiveDocumentDateDialog.title = '修改收款日期'
      this.receiveDocumentDateDialog.show = true
    },
    doReceiveDocumentDate() {
      this.$refs['receiveForm'].validate(validate => {
        if (validate) {
          const data = []
          for (let item of this.selected) {
            data.push({
              cbId: item.id,
              cbReceiveDocumentDate: this.receiveDocumentDateDialog.date,
            })
          }
          updateBillsSelective(data).then(() => {
            this.$message.success('成功')
            this.receiveDocumentDateDialogClose()
          })
        }
      })
    },
    receiveDocumentDateDialogClose() {
      this.receiveDocumentDateDialog.show = false
      this.$refs['receiveForm'].resetFields()
      this.refreshList()
    },
    infoHandleSizeChange(val) {
      this.infoPayTable.pageInfo.size = val
      this.initMainTable()
    },
    infoHandleCurrentChange(val) {
      this.infoPayTable.pageInfo.index = val
      this.initMainTable()
    },
  },
}
</script>

<style lang="scss" scoped>
.openOrder {
  height: 87%;
  width: 100%;
  padding-left: 10px;
  padding-top: 10px;
}

.openOrderBox {
  // height: calc(100vh - 300px);
  // width: 100%;
  // display: flex;
  // .openOrderLeft {
  //   flex: 1;
  // }
}

.openTitle {
  font-size: 13px;
}

.btn {
  padding-top: 10px;
  padding-bottom: 10px;
}

::v-deep .splitter-pane-resizer.horizontal {
  margin-top: -15px;
}
</style>
